package io.renren.modules.lucky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.app.form.out.AppSysNoticeForm;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.lucky.dao.AppSysNoticeDao;
import io.renren.modules.lucky.entity.AppSysNoticeEntity;
import io.renren.modules.lucky.service.AppSysNoticeService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("appSysNoticeService")
public class AppSysNoticeServiceImpl extends ServiceImpl<AppSysNoticeDao, AppSysNoticeEntity> implements AppSysNoticeService {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AppSysNoticeEntity> page = this.page(
                new Query<AppSysNoticeEntity>().getPage(params), new QueryWrapper<AppSysNoticeEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<AppSysNoticeForm> queryNoticeList(String userId, String page, String limit) throws InvocationTargetException, IllegalAccessException {

        QueryWrapper<AppSysNoticeEntity> noticeWrapper = new QueryWrapper<AppSysNoticeEntity>();
        noticeWrapper.ne("notice_flag", 0);
        noticeWrapper.and(wrapper -> wrapper.eq("user_id", userId).or().isNull("user_id"));
        noticeWrapper.orderByDesc("create_time");
        noticeWrapper.last("limit " + page + "," + limit);
        List<AppSysNoticeEntity> list = baseMapper.selectList(noticeWrapper);

        List<AppSysNoticeForm> noticeList = new ArrayList<>();
        for (AppSysNoticeEntity noticeEntity : list) {
            AppSysNoticeForm noticeForm = new AppSysNoticeForm();
            BeanUtils.copyProperties(noticeForm, noticeEntity);
            noticeList.add(noticeForm);
        }
        Assert.isNull(list, "公告为空");
        return noticeList;
    }

    public boolean updateNotice(String noticeId, String user_token, String userId) {
        String id = jwtUtils.getClaimByToken(user_token).getSubject();
        if (id.equals(userId)) {
            AppSysNoticeEntity noticeEntity = new AppSysNoticeEntity();
            noticeEntity.setNoticeFlag(2);
            return this.update(noticeEntity, new QueryWrapper<AppSysNoticeEntity>().eq("id", noticeId));
        } else {
            throw new RRException("请求用户id与token不匹配");
        }
    }

}